package com.shixi.shixitraining.shixitraining.ui.tabhome.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shixi.shixitraining.shixitraining.R;
import com.shixi.shixitraining.shixitraining.base.BaseActivity;
import com.shixi.shixitraining.shixitraining.constant.Constants;
import com.shixi.shixitraining.shixitraining.http.CallbackImple;
import com.shixi.shixitraining.shixitraining.http.HttpUtil;
import com.shixi.shixitraining.shixitraining.ui.tabhome.entity.OverseaSubmitApplyBean;
import com.shixi.shixitraining.shixitraining.ui.tabhome.entity.OversearApplyBean;
import com.shixi.shixitraining.shixitraining.ui.tabhome.entity.UpdataBean;
import com.shixi.shixitraining.shixitraining.util.ToastUtil;
import com.shixi.shixitraining.shixitraining.util.UserManager;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;

public class OverseaApplyActivity extends BaseActivity implements View.OnClickListener {

    private EditText mWechat;
    private EditText mPhone;
    private TextView mResumeTv;
    private TextView mLetterTv;
    private TextView mOverseaApply;
    private int job;
    private String letterName;
    private String letterSource;
    private String resumeName;
    private String resumeSource;
    String cachePath = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_resume);
        Intent intent = getIntent();
        if (intent!=null){
            Bundle bundle = intent.getExtras();
            String id = bundle.getString("id");
            requestOverseaApply(id);
        }
        ImageView mBackImg = (ImageView) findViewById(R.id.iv_back);
        mBackImg.setOnClickListener(this);
        initView();


    }
    public String path;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==Activity.RESULT_OK){
            Uri uri = data.getData();
                      if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
                          path = uri.getPath();
                          Log.i("path",path);
                          mResumeTv.setText(path);
                                Toast.makeText(this, path +"11111",Toast.LENGTH_SHORT).show();
                            return;
                          }
        }
    }

    private void initView() {
        mWechat = (EditText) findViewById(R.id.edt_wechat_num);
        mPhone = (EditText) findViewById(R.id.edt_phone_num);
        mResumeTv = (TextView) findViewById(R.id.up_resume_title);
        mLetterTv = (TextView) findViewById(R.id.up_letter_title);
        mOverseaApply = (TextView) findViewById(R.id.tv_employment_apply);

        if (TextUtils.isEmpty(mWechat.toString())){
            return;
        }else if (TextUtils.isEmpty(mPhone.toString())){
            return;
        }

        mResumeTv.setOnClickListener(this);
        mLetterTv.setOnClickListener(this);
        mOverseaApply.setOnClickListener(this);

    }

    private void requestOverseaApply(String id) {
        String token = UserManager.getInstance().getToken();
        String userId = UserManager.getInstance().getUserId();

        String url= Constants.OVERSEAAPPLY+"&userId="+userId+"&token="+token+"&job="+id;

        HttpUtil.getInstance().getApiInterface().overseaApply(url).enqueue(new CallbackImple<OversearApplyBean>() {
            @Override
            public void onError(Call<OversearApplyBean> call, Throwable t) {
                ToastUtil.showShortToast(OverseaApplyActivity.this,t.getMessage());
            }

            @Override
            public void onSuccess(Call<OversearApplyBean> call, OversearApplyBean response) {
                if (response.getData()!=null){
                    if (response.getStatus()==200){

                        OversearApplyBean.DataBean data = response.getData();
                        job = data.getJob();
                        OversearApplyBean.DataBean.MemberBean memberBean = data.getMember();
                        String title = data.getTitle();
                        String intl_code = memberBean.getIntl_code();
                        String telephone = memberBean.getTelephone();
                        String wechat = memberBean.getWechat();

                        if (mPhone==null){
                            mPhone.setText(telephone.toString());
                        }
                        if (mWechat==null){
                            mWechat.setText(wechat.toString());
                        }

                    }else {
                        ToastUtil.showShortToast(OverseaApplyActivity.this,response.getMsg());
                    }
                }else {
                    ToastUtil.showShortToast(OverseaApplyActivity.this,"数据为空");
                }

            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.up_resume_title:
                updateResume();
                break;
            case R.id.up_letter_title:
                updateLetter();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_employment_apply:
                SubmitApply();
                break;
        }
    }

    private void SubmitApply() {
        String token = UserManager.getInstance().getToken();
        String userId = UserManager.getInstance().getUserId();
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("userId",userId);
        map.put("job",job);
        map.put("resume_path",resumeSource);
        map.put("resume_name",resumeName);
        map.put("letter_path",letterSource);
        map.put("letter_name",letterName);
        map.put("telephone",mPhone);
        map.put("wechat",mWechat);

        HttpUtil.getInstance().getApiInterface().overseaSubmitApply(map).enqueue(new CallbackImple<OverseaSubmitApplyBean>() {
            @Override
            public void onError(Call<OverseaSubmitApplyBean> call, Throwable t) {
                ToastUtil.showShortToast(OverseaApplyActivity.this,t.getMessage());
            }

            @Override
            public void onSuccess(Call<OverseaSubmitApplyBean> call, OverseaSubmitApplyBean response) {

                if (response.getStatus()==200){
                    if (response.getData()!=null){
                        OverseaSubmitApplyBean.DataBean data = response.getData();
                        String number = data.getNumber();

                        ToastUtil.showShortToast(OverseaApplyActivity.this,number);

                    }else {
                        ToastUtil.showShortToast(OverseaApplyActivity.this,"数据为空");
                    }

                }else {
                    ToastUtil.showShortToast(OverseaApplyActivity.this,"数据加载失败");
                }
            }
        });


    }

    private void updateLetter() {
        Intent intent1=new Intent(Intent.ACTION_GET_CONTENT);
        intent1.setType("*/*");//无类型限制
        intent1.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent1, 1);
        File file=new File(cachePath);
//        Map<String,Object> map=new HashMap<>();
//        map.put("fiel",file);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        HttpUtil.getInstance().getApiInterface().upload(body).enqueue(new CallbackImple<UpdataBean>() {
            @Override
            public void onError(Call<UpdataBean> call, Throwable t) {
                ToastUtil.showShortToast(OverseaApplyActivity.this, t.getMessage());
                String message = t.getMessage();
                Log.i("message",message);
            }

            @Override
            public void onSuccess(Call<UpdataBean> call, UpdataBean response) {
                UpdataBean.DataBean data = response.getData();


            }
        });

//        HttpUtil.getInstance().getApiInterface().updataFile(map).enqueue(new CallbackImple<UpdataBean>() {
//            @Override
//            public void onError(Call<UpdataBean> call, Throwable t) {
//                ToastUtil.showShortToast(OverseaApplyActivity.this, t.getMessage());
//            }
//
//            @Override
//            public void onSuccess(Call<UpdataBean> call, UpdataBean response) {
//
//                if (response.getStatus()==200){
//                    ToastUtil.showShortToast(OverseaApplyActivity.this,response.getMsg());
//                    if (response.getData()!=null){
//                        UpdataBean.DataBean data = response.getData();
//                        letterName = data.getFilename();
//                        letterSource = data.getSource();
//                        mLetterTv.setText(letterName);
//                    }else {
//                        ToastUtil.showShortToast(OverseaApplyActivity.this,"数据为空");
//                    }
//                }else {
//                    ToastUtil.showShortToast(OverseaApplyActivity.this,"数据加载失败");
//                }
//            }
//        });


    }



    private void updateResume() {

        Intent intent1=new Intent(Intent.ACTION_GET_CONTENT);
        intent1.setType("*/*");//无类型限制
        intent1.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent1, 1);
        getDiskCacheDir(this);
            File file=new File(cachePath);
            Map<String,Object> map=new HashMap<>();
            map.put("file",file);
        HttpUtil.getInstance().getApiInterface().updataFile(map).enqueue(new CallbackImple<UpdataBean>() {
            @Override
            public void onError(Call<UpdataBean> call, Throwable t) {
                ToastUtil.showShortToast(OverseaApplyActivity.this,t.getMessage());
            }

            @Override
            public void onSuccess(Call<UpdataBean> call, UpdataBean response) {
                if (response.getStatus()==200){
                    if (response.getData()!=null){
                        UpdataBean.DataBean data = response.getData();
                        resumeName = data.getFilename();
                        resumeSource = data.getSource();
                        mResumeTv.setText(resumeName);

                    }else {
                        ToastUtil.showShortToast(OverseaApplyActivity.this,response.getMsg());
                    }

                }else {
                    ToastUtil.showShortToast(OverseaApplyActivity.this,"数据加载失败");
                }
            }
        });


//        String perms = Manifest.permission.READ_EXTERNAL_STORAGE;
//        if (EasyPermissions.hasPermissions(this,perms)){
//            getDiskCacheDir(this);
//            File file=new File(path);
//            Map<String,Object> map=new HashMap<>();
//            map.put("file",file);
//            OkGo.<UpdataBean>post(Constants.UPDATAFILE).params("file",new File(path)).execute(new JsonCallBack<UpdataBean>() {
//                @Override
//                public void onParseSuccess(String response, int code, String msg, UpdataBean data) {
//                    UpdataBean.DataBean mData = data.getData();
//                     resumeName = mData.getFilename();
//                     resumeSource = mData.getSource();
//                     mResumeTv.setText(resumeName);
//                }
//            });
//
//        }else {
//            EasyPermissions.requestPermissions(this,"实习网请求获取读取SD卡权限", 1001,perms);
//        }



    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }





    //获取文件路径
    public String getDiskCacheDir(Context context) {

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalFilesDir(".doc").getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }


}
